package com.algorithm.base;

/**
 * 反转单词
 *
 * @author Amadeus
 * @date 2023/10/25
 */
public class ReverseWords {

    /**
     * 反转单词
     *
     * @param s s
     * @return {@link String}
     */
    public static String reverseWords(String s) {
        char[] chars = s.toCharArray();
        int slow = 0;
        for (int i = 0; i < chars.length - 1; i++) {
            if (slow != 0 && chars[i] == ' ') {
                chars[slow] = ' ';
                slow++;
            }
            if (chars[i] != ' ') {

                chars[slow] = chars[i];
                slow++;
            }
        }
        //全部翻转
        change(chars, 0, slow);
        //翻转每个单词
        for (int i = 0; i < chars.length - 1; i++) {
            int flag = 0;
            if (chars[i] != ' ') {
                flag++;
            }
            change(chars, i, flag);
        }
        return String.valueOf(chars);
    }

    public static void change(char[] chars, int x, int y) {
        while (x < y) {
            char flag = chars[x];
            chars[x] = chars[y];
            chars[y] = flag;
            x++;
            y--;
        }
    }

    public static void main(String[] args) {
        System.out.println(reverseWords("hello world"));
    }

}
